package indi.lddsdu.spider.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import indi.lddsdu.spider.bean.Record;


/**
 * Created by jack on 18/6/4.
 */

@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class RecordDao {
    private Logger logger = LoggerFactory.getLogger(RecordDao.class);
    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession(){
        try {
            return sessionFactory.getCurrentSession();
        }catch (Exception e){
            System.out.println(e);
        }
        return null;
    }

    //添加Record实例
    public void addRecord(Record record){
        getSession().save(record);
    }

    //通过url来查询获得到当前的已经爬取得链接中是否存在
    public boolean alreadyInDatabase(String url){
        String hql = "from "+Record.class.getName()+" as record where record.url=:url";
        Query query = getSession().createQuery(hql);
        query.setString("url", url);
        List<Record> list = query.list();
        if (list.size() == 0){
            logger.info(String.format("url: %s is new", url));
            return false;
        }
        logger.info(String.format("url: %s already in table", url));
        return true;
    }
}